package com.hisense.hiioc.hismartplate.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hisense.hiioc.hismartplate.robot.message.Directive;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Auther:biexiande@hisense.com
 * @date:2017/8/11 17:04
 * @des
 */
public class StringUtil {

    private static Logger logger = LogManager.getLogger(StringUtil.class);
    /**
     * 判断字符串是否为空，null,空字符串，空格字符串都是返回true
     * @param str
     * @return 是空，返回true，否则false
     */
    public static boolean isNullOrEmpty(String str) {
        if (str == null || str.trim().length() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 判断字符串是否不为空，null,空字符串，空格字符串都是返回false
     *
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        if (str == null || str.trim().length() == 0) {
            return false;
        }
        return true;
    }

    /**
     * 格式化对象为json字符串
     *
     * @param t
     *            对象
     * @return json 字符串，转换失败，返回空字符串
     */
    public static <T> String toJson(T t) {
        ObjectMapper mapper = new ObjectMapper();
        String json;
        try {
            json = mapper.writeValueAsString(t);
            return json;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getDirectiveJson(Directive directive){
        return StringUtil.toJson(new HashMap() {{
                                     put("directive", directive);
                                 }}
        );
    }


    /**
     * 格式化对象为json字符串
     *如果值为空不参加序列化
     * @param t
     *            对象
     * @return json 字符串，转换失败，返回空字符串
     */
    public static <T> String toJsonIngoreNull(T t) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String json;
        try {
            json = mapper.writeValueAsString(t);
            return json;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 比较两个字符串的是否相等，不区分大小写
     *
     * @param source
     * @param dest
     * @return
     */
    public static boolean equals(String source, String dest) {
        if (source == null && dest == null)
            return true;
        if (source == null && dest != null) {
            return false;
        }
        if (source != null && dest == null) {
            return false;
        }
        return source.equalsIgnoreCase(dest);
    }

    /**
     *
     * @param json
     * @return
     */
    public static <T> T fromJson(String json, TypeReference<T> ref) {
        if (isNullOrEmpty(json) || ref == null)
            return null;
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return mapper.readValue(json, ref);
        } catch (IOException e) {
            return null;
        }
    }

    /**
     *
     * @param json
     */
    public static <T> T fromJson(String json, Class<T> ref) {
        if (isNullOrEmpty(json) || ref == null)
            return null;
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return mapper.readValue(json, ref);
        } catch (IOException e) {
            logger.error(e);
            return null;
        }
    }

    /**
     * 字符串转Integer
     *
     * @param str
     * @return
     *
     */
    public static Integer toInteger(String str) {
        if (isNullOrEmpty(str))
            return 0;
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 生成字母和数字组成的随机数
     *
     * @param length
     * @param num
     * @return
     */
    public static String createRandomCode(int length, long num) {
        List<String> results = new ArrayList<String>();
        for (int j = 0; j < num; j++) {
            String val = "";

            Random random = new Random();
            for (int i = 0; i < length; i++) {
                String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字

                if ("char".equalsIgnoreCase(charOrNum)) // 字符串
                {
                    int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
                    val += (char) (choice + random.nextInt(26));
                } else if ("num".equalsIgnoreCase(charOrNum)) // 数字
                {
                    val += String.valueOf(random.nextInt(10));
                }
            }
            val = val.toLowerCase();
            if (results.contains(val)) {
                continue;
            } else {
                results.add(val);
            }
        }
        String result = String.join("", results);
        return result;
    }

    public static String CreateRandomString(int digits){
        Date n = new Date();
        long timeMill = n.getTime();
        Random rnd = new Random(timeMill);
        StringBuilder sb = new StringBuilder(digits);
        for(int i=0; i < digits; i++){
            sb.append((char)('0' + rnd.nextInt(10)));
        }
        return sb.toString();
    }

    /**
     * 获取当前时间戳
     * @return
     */
    public static String getTimestamp(){
        return String.valueOf(System.currentTimeMillis());
    }

    public static String urlEncode(String str) {
        String result = null;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {

    }


}